package openjdk.thread;


/**
 * Created by boot on 1/10/16.
 * java中的sleep()和wait()的区别
 */
public class ThreadWait {
    public static void main(String[] args) {

        try {
            System.out.println("当前线程：" + Thread.currentThread().getName() + "休眠3秒钟");
            Thread.sleep(3000);
            System.out.println("main 休眠完成！");
        } catch (Exception e) {
            e.printStackTrace();
        }
        new Thread(new Thread01(), "Thread 01").start();
        new Thread(new Thread02(), "Thread 02").start();


    }

    private static class Thread01 implements Runnable {
        @Override
        public void run() {
            synchronized (ThreadWait.class) {
                System.out.println("enter thread01 ...");
                System.out.println("thread01 is waiting...");
                try {
                    //调用wait()方法，线程会放弃对象锁，进入等待此对象的等待锁定池
                    // 即此线程被挂起，直到接收到notify通知
                    ThreadWait.class.wait();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println("thread01 is going on ...");
                System.out.println("thread01 is over!");
            }
        }
    }


    private static class Thread02 implements Runnable {

        @Override
        public void run() {
            synchronized (ThreadWait.class) {
                System.out.println("enter thread02 ...");
                System.out.println("thread02 is waiting...");

                //只有针对此对象调用notify()方法后,本线程才进入对象锁定池准备获取对象锁进入运行状态。
                //如果我们把代码：TestD.class.notify();给注释掉，即TestD.class调用了wait()方法，
                //但是没有调用notify()方法，则线程永远处于挂起状态。
                ThreadWait.class.notify();

                try {
                    System.out.println("当前线程：" + Thread.currentThread().getName() + "休眠5秒钟");
                    Thread.sleep(5000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println("thread02 is going on....");
                System.out.println("thread02 is over.");

            }
        }
    }
}
